package com.liumin.comlink.http.rx;


import android.util.Log;
import android.widget.Toast;

import androidx.annotation.MainThread;

import com.liumin.comlink.http.exception.ApiException;
import com.liumin.comlink.http.exception.ExceptionHandle;
import com.liumin.publiclib.helper.ContextApp;
import com.liumin.publiclib.helper.JSONHelper;

import io.reactivex.observers.ResourceObserver;

/**
 * 简化retrofit网络请求,统一异常处理(Observer)
 * 2019/12/25 15:01
 *
 * @author LiuWeiHao
 */
public abstract class BaseObserver<T> extends ResourceObserver<T> {

    private final String TAG = "onError";

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void onError(Throwable e) {
        Log.i(TAG, "e.message:" + e.getMessage());
        e.printStackTrace();
        ApiException apiException = ExceptionHandle.handleException(e);
        Log.i(TAG, "apiException:" + JSONHelper.toJsonString(apiException));
        onErrorResponse(new Throwable(apiException.getMessage(), e));
    }

    public abstract void onErrorResponse(Throwable throwable);

    public void onError(Throwable t, boolean isDialog) {
        if (!isDialog && t != null) {
            onFileException(t);
        }
    }

    @Override
    public void onComplete() {

    }

    @MainThread
    private void onFileException(Throwable throwable) {
        if (ContextApp.app() != null && throwable != null) {
            Toast.makeText(ContextApp.app(), throwable.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }


}
